import axios from 'axios'
import {Message} from 'element-ui'
import {showLoading, hideLoading} from '@/utils/LoadingUtil'

const apiBasUrl = 'http://easyblog.itgone.com'

const axiosInstance = axios.create({
  baseURL: apiBasUrl, // 设置请求的base url
  timeout: 40000 // 超时时长
})

// 通用公用方法
const req = (method, url, params, reqData) => {
  const reqParams = {
    method: method,
    url: url,
    headers: {},
    data: reqData,
    params: params
  }
  return axiosInstance.request(reqParams).then(res => res.data)
}

// http请求拦截器
axiosInstance.interceptors.request.use(res => {
  // 发送请求前要做的事儿，例如统一cookie、设置请求头header等
  showLoading()
  return res
}, (error) => {
  // 请求发生错误时在这里处理
  hideLoading()
  return Promise.reject(error)
})

// http响应拦截器
axiosInstance.interceptors.response.use(res => {
  // 请求成功时对响应数据做处理，做数据统一处理，常处理登录失败与失效
  hideLoading()
  const data = res.data
  if (!http.isSuccess(data)) {
    Message.error(data.msg)
  }
  return res
}, (error) => {
  // 请求失败时在这里处理
  hideLoading()
  return Promise.reject(error)
})

const http = {
  post: (url, param) => req('post', url, null, param),
  delete: (url, param) => req('delete', url, param),
  put: (url, param) => req('put', url, null, param),
  get: (url, param) => req('get', url, param),
  isSuccess: (apiResult) => apiResult !== undefined && apiResult.code !== undefined && apiResult.code === 0
}
export {
  http
}
